<template>
  <div class="conversation-detail-container">
    <div class="detail-header">
      <div class="header-left">
        <el-button @click="goBack" class="back-button" size="large">
          <el-icon>
            <Back />
          </el-icon>
          返回
        </el-button>
        <div class="service-info">
          <el-avatar :src="serviceInfo.avatar" :size="40" class="service-avatar">
            <span>{{ serviceInfo.nickname?.charAt(0) }}</span>
          </el-avatar>
          <div class="service-details">
            <h3 class="service-name">{{ serviceInfo.nickname || '客服' }}</h3>
            <span class="service-id">ID: {{ serviceInfo.id }}</span>
          </div>
        </div>
      </div>
      <div class="header-right">
        <el-tag type="success" effect="light">在线客服</el-tag>
      </div>
    </div>

    <div class="chat-layout">
      <!-- 左侧用户列表 -->
      <div class="chat-sidebar">
        <div class="sidebar-header">
          <h4>聊天用户</h4>
          <el-input v-model="userSearch" placeholder="搜索用户" clearable size="small" class="user-search">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>

        <div class="user-list" v-loading="usersLoading">
          <div v-for="user in filteredUserList" :key="user.id" class="user-item"
            :class="{ active: currentUserId === user.id }" @click="selectUser(user)">
            <div class="user-avatar-wrapper">
              <el-avatar :src="user.avatar" :size="44" class="user-avatar">
                <span>{{ user.nickname?.charAt(0) }}</span>
              </el-avatar>
              <div v-if="user.isOnline" class="online-indicator"></div>
            </div>
            <div class="user-info">
              <div class="user-name">
                {{ user.nickname }}
                <span v-if="user.isTyping" class="typing-text">正在输入...</span>
              </div>
              <div class="last-message">
                <span v-if="user.lastMessage?.includes('[图片]')" class="image-label">
                  <el-icon>
                    <Picture />
                  </el-icon> 图片
                </span>
                <span v-else>{{ user.lastMessage || '暂无消息' }}</span>
              </div>
            </div>
            <div class="user-meta">
              <div class="time">{{ user.lastTime }}</div>
              <el-badge v-if="user.unread > 0" :value="user.unread" class="unread-badge" />
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="!usersLoading && filteredUserList.length === 0" class="empty-users">
            <el-empty description="暂无聊天用户" :image-size="80" />
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-main">
        <div v-if="!currentUserId" class="empty-chat">
          <div class="empty-content">
            <el-icon class="empty-icon">
              <ChatDotRound />
            </el-icon>
            <h3>选择一个用户开始聊天</h3>
            <p>从左侧用户列表中选择用户，开始进行对话</p>
          </div>
        </div>

        <template v-else>
          <!-- 聊天头部 -->
          <div class="chat-header">
            <div class="chat-user-info">
              <el-avatar :src="currentUser?.avatar" :size="36">
                <span>{{ currentUser?.nickname?.charAt(0) }}</span>
              </el-avatar>
              <div class="chat-user-details">
                <span class="chat-user-name">{{ currentUser?.nickname }}</span>

              </div>
            </div>
            <div class="chat-actions">
              <el-button size="small" text>
                <el-icon>
                  <MoreFilled />
                </el-icon>
              </el-button>
            </div>
          </div>

          <!-- 消息区域 -->
          <div class="chat-messages" ref="messagesContainer" v-loading="loading">
            <div v-for="(msg, index) in messages" :key="index" class="message-wrapper"
              :class="{ 'message-self': msg.senderId === serviceInfo.id }">
              <div class="message-item">
                <el-avatar :src="msg.senderId === serviceInfo.id ? serviceInfo.avatar : currentUser?.avatar" :size="32"
                  class="message-avatar">
                  <span>{{ (msg.senderId === serviceInfo.id ? serviceInfo.nickname : currentUser?.nickname)?.charAt(0)
                  }}</span>
                </el-avatar>
                <div class="message-content">
                  <div class="message-info">
                    <span class="sender-name">
                      {{ msg.senderId === serviceInfo.id ? serviceInfo.nickname : currentUser?.nickname }}
                    </span>
                    <span class="message-time">{{ msg.time }}</span>
                  </div>
                  <div class="message-bubble" :class="{ 'image-message': msg.type === 'image' }">
                    <!-- 文本消息 -->
                    <template v-if="msg.type === 'text' || !msg.type">
                      {{ msg.content }}
                    </template>
                    <!-- 图片消息 -->
                    <template v-else-if="msg.type === 'image'">
                      <el-image :src="msg.content" :preview-src-list="[msg.content]" fit="cover" class="message-image"
                        :z-index="9999" loading="lazy" />
                    </template>
                  </div>
                </div>
              </div>
            </div>

            <!-- 正在输入指示器 -->
            <div v-if="currentUser?.isTyping" class="typing-indicator">
              <div class="typing-avatar">
                <el-avatar :src="currentUser.avatar" :size="24">
                  <span>{{ currentUser.nickname?.charAt(0) }}</span>
                </el-avatar>
              </div>
              <div class="typing-animation">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="chat-input">
            <div class="input-container">
              <el-input v-model="messageInput" type="textarea" :rows="1" :autosize="{ minRows: 1, maxRows: 4 }"
                placeholder="输入消息..." resize="none" class="message-input" @keyup.enter.exact.prevent="sendMessage"
                @input="handleTyping" />
              <div class="input-actions">
                <input type="file" ref="fileInput" accept="image/*" style="display: none" @change="handleFileChange" />
                <el-button @click="triggerFileUpload" class="action-btn" text>
                  <el-icon>
                    <Picture />
                  </el-icon>
                </el-button>
                <el-button type="primary" @click="sendMessage" :disabled="!messageInput.trim()" class="send-btn"
                  size="small">
                  <el-icon>
                    <Promotion />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onBeforeUnmount, nextTick } from 'vue'
import { Search, Refresh, Back, Loading, Picture, MoreFilled, ChatDotRound, Promotion } from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import {
  getCustomerServiceDetail,
  getCustomerChatUsers,
  getChatHistory,
  sendChatMessage,
  uploadChatImage
} from '@/api/customer-service'

// 接口类型定义
interface CustomerService {
  id: string | number
  nickname: string
  avatar: string
  created_at: string
}

interface User {
  id: string | number
  nickname: string
  avatar: string
  lastMessage?: string
  lastTime?: string
  unread: number
  isOnline?: boolean
  isTyping?: boolean
}

interface Message {
  id: string | number
  content: string
  senderId: string | number
  receiverId: string | number
  time: string
  status: 'sent' | 'delivered' | 'read'
  type?: 'text' | 'image' | 'file'
}

const router = useRouter()
const route = useRoute()

// 客服ID
const serviceId = computed(() => route.query.id as string)

// WebSocket连接
let ws: WebSocket | null = null

// 客服信息
const serviceInfo = ref<CustomerService>({} as CustomerService)
const infoLoading = ref(false)
const usersLoading = ref(false)
const loading = ref(false)

// 聊天相关
const userSearch = ref('')
const currentUserId = ref<string | number>('')
const messageInput = ref('')
const messages = ref<Message[]>([])
const messagesContainer = ref<HTMLElement | null>(null)
const userList = ref<User[]>([])

// 分页参数
const userListParams = reactive({
  page_no: 1,
  page_size: 20,
  keyword: ''
})

const chatHistoryParams = reactive({
  page_no: 1,
  page_size: 20
})

// 当前选中的用户
const currentUser = computed(() => {
  return userList.value.find(user => user.id === currentUserId.value)
})

// 筛选用户列表
const filteredUserList = computed(() => {
  if (!userSearch.value) return userList.value
  return userList.value.filter(user =>
    user.nickname.toLowerCase().includes(userSearch.value.toLowerCase())
  )
})

// 文件上传相关
const fileInput = ref<HTMLInputElement | null>(null)

// 触发文件选择
const triggerFileUpload = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 处理文件选择变化
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files

  if (!files || files.length === 0 || !currentUserId.value) {
    return
  }

  const file = files[0]

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  // 检查文件大小 (限制为5MB)
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }

  // 显示上传中的消息
  const tempId = Date.now()
  const tempMessage: Message = {
    id: tempId,
    content: URL.createObjectURL(file),
    senderId: serviceInfo.value.id,
    receiverId: currentUserId.value,
    time: formatTime(new Date()),
    status: 'sent',
    type: 'image'
  }

  // 添加到消息列表
  messages.value.push(tempMessage)
  scrollToBottom()

  // 上传图片
  try {
    loading.value = true
    const response = await uploadChatImage(file, {
      kefu_id: serviceId.value,
      customer_id: currentUserId.value
    })

    // 上传成功，更新消息
    if (response && response.url) {
      // 更新临时消息的内容为服务器返回的URL
      const index = messages.value.findIndex(msg => msg.id === tempId)
      if (index !== -1) {
        messages.value[index].content = response.url
        messages.value[index].id = response.id || tempId
      }

      // 更新用户列表中的最后消息
      const user = userList.value.find(u => u.id === currentUserId.value)
      if (user) {
        user.lastMessage = '[图片]'
        user.lastTime = '刚刚'
      }

      // 通过WebSocket发送消息（如果可用）
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
          type: 'message',
          data: {
            id: response.id || tempId,
            content: response.url,
            sender_id: serviceInfo.value.id,
            receiver_id: currentUserId.value,
            time: formatTime(new Date()),
            status: 'sent',
            type: 'image'
          }
        }))
      }
    }
  } catch (error) {
    console.error('上传图片失败', error)
    ElMessage.error('上传图片失败')

    // 移除临时消息
    messages.value = messages.value.filter(msg => msg.id !== tempId)
  } finally {
    loading.value = false
    // 清空文件输入框，允许重复选择同一文件
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  }
}

// 获取客服详情
const getServiceInfo = async () => {
  if (!serviceId.value) {
    ElMessage.error('客服ID不能为空')
    return
  }

  infoLoading.value = true
  try {
    const response = await getCustomerServiceDetail(serviceId.value)
    console.log(response);
    serviceInfo.value = response || {}
  } catch (error) {
    console.error('获取客服详情失败', error)
    ElMessage.error('获取客服详情失败')
    // 模拟数据
    serviceInfo.value = {}
  } finally {
    infoLoading.value = false
    // 获取用户列表
    getUserList()
    // 建立WebSocket连接
    connectWebSocket()
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    const response = await getCustomerChatUsers(serviceId.value, {
      page_no: userListParams.page_no,
      page_size: userListParams.page_size,
      keyword: userListParams.keyword || undefined
    })

    if (response && response.list) {
      // 转换API返回数据为组件所需格式
      userList.value = response.list.map((item: any) => ({
        id: item.customer_id,
        nickname: item.customer_info?.nickname || '',
        avatar: item.customer_info?.avatar || '',
        lastMessage: item.last_message || '暂无消息',
        lastTime: item.last_message_time || '',
        unread: item.no_read_num || 0
      }))
    }
  } catch (error) {
    console.error('获取聊天用户列表失败', error)
    ElMessage.error('获取聊天用户列表失败')
    // 模拟数据
    userList.value = []
  }
}

// 选择用户
const selectUser = (user: User) => {
  currentUserId.value = user.id
  // 清空未读消息数
  const selectedUser = userList.value.find(u => u.id === user.id)
  if (selectedUser) {
    selectedUser.unread = 0
  }
  // 获取历史消息
  getHistoryMessages()
}

// 获取历史消息
const getHistoryMessages = async () => {
  if (!currentUserId.value) return

  loading.value = true
  messages.value = []

  try {
    const response = await getChatHistory({
      kefu_id: serviceId.value,
      customer_id: currentUserId.value,
      page_no: chatHistoryParams.page_no,
      page_size: chatHistoryParams.page_size
    })

    if (response && response.list) {
      // 转换API返回数据为组件所需格式
      messages.value = response.list.map((item: any) => {
        return {
          id: item.id,
          content: item.content,
          senderId: item.send_type === 2 ? item.kefu_id : '',
          receiverId: item.send_type === 1 ? item.customer_id : '',
          time: item.created_at,
          status: item.is_read || 'read',
          type: item.message_type
        }
      })
    }
  } catch (error) {
    console.error('获取历史消息失败', error)
    ElMessage.error('获取历史消息失败')
    // 模拟历史消息数据
    messages.value = []
  } finally {
    loading.value = false

    // 滚动到底部
    scrollToBottom()
  }
}

// 处理用户输入事件
let typingTimeout: number | null = null
const handleTyping = () => {
  if (!currentUserId.value || !ws) return

  // 清除之前的计时器
  if (typingTimeout !== null) {
    clearTimeout(typingTimeout)
  }

  // 发送正在输入消息
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({
      type: 'typing',
      data: {
        kefu_id: serviceId.value,
        user_id: currentUserId.value
      }
    }))
  }

  // 设置新的计时器
  typingTimeout = window.setTimeout(() => {
    typingTimeout = null
  }, 3000)
}

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim() || !currentUserId.value) return

  const newMessage: Message = {
    id: Date.now(),
    content: messageInput.value,
    senderId: serviceInfo.value.id,
    receiverId: currentUserId.value,
    time: formatTime(new Date()),
    status: 'sent',
    type: 'text'
  }



  // 更新用户列表中的最后消息
  const user = userList.value.find(u => u.id === currentUserId.value)
  if (user) {
    user.lastMessage = messageInput.value
    user.lastTime = '刚刚'
  }


  // 清空输入框
  const content = messageInput.value
  // 通过API发送消息
  try {
    const response = await sendChatMessage({
      kefu_id: serviceId.value,
      customer_id: currentUserId.value,
      content: content,
      type: 'text'
    });

    console.log('发送文本消息：', response);

    if (response.code == 1) {
      // 添加到消息列表
      messages.value.push(newMessage);
      messageInput.value = ''
      // 滚动到底部
      scrollToBottom()
    } else {
      ElMessage.error(response.msg)
    }
  } catch (error) {
    console.error('发送消息失败', error)
    ElMessage.error('发送消息失败')
  }

  // 通过WebSocket发送消息（如果可用）
  //   if (ws && ws.readyState === WebSocket.OPEN) {
  //     ws.send(JSON.stringify({
  //       type: 'message',
  //       data: {
  //         id: newMessage.id,
  //         content: content,
  //         sender_id: serviceInfo.value.id,
  //         receiver_id: currentUserId.value,
  //         time: newMessage.time,
  //         status: 'sent',
  //         type: 'text'
  //       }
  //     }))
  //   }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 连接WebSocket
const connectWebSocket = () => {
  // 获取后端WebSocket地址
  // 实际项目中替换为真实的WebSocket地址
  //   const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const protocol = 'wss:';
  const host = "adsapi.hxjpayment.cn/wss"
  const wsUrl = `${protocol}//${host}`

  try {
    ws = new WebSocket(wsUrl)

    ws.onopen = () => {
      console.log('WebSocket连接已建立')
      // 发送认证信息
      if (ws) {
        ws.send(JSON.stringify({
          type: 'auth',
          data: {
            kefu_id: serviceId.value
          }
        }))
      }
    }

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        console.log('收到WebSocket消息', data)

        switch (data.type) {
          case 'message':
            console.log('message_data:', data);
            // 处理新消息
            const message = {
              id: data.data.id || Date.now(),
              content: data.data.content,
              senderId: data.data.senderId,
              receiverId: data.data.receiverId,
              time: data.data.time,
              status: data.data.status,
              type: data.data.type
            }
            handleNewMessage(message);

            ws.send(JSON.stringify({
              type: 'read',
              data: {
                chat_id: message.id,
              }
            }))

            break

          case 'auth':
            ws.send(JSON.stringify({
              type: 'ping',
              data: {
                kefu_id: serviceId.value
              }
            }))
            break

          case 'pong':
            setTimeout(() => {
              ws.send(JSON.stringify({
                type: 'ping',
                data: {
                  kefu_id: serviceId.value
                }
              }))
            }, 3000)

            break

          case 'user_online':
            // 处理用户上线事件
            updateUserStatus(data.data.user_id, true)
            break

          case 'user_offline':
            // 处理用户下线事件
            updateUserStatus(data.data.user_id, false)
            break

          case 'typing':
            // 处理用户正在输入事件
            updateUserTypingStatus(data.data.user_id, true)
            setTimeout(() => {
              updateUserTypingStatus(data.data.user_id, false)
            }, 3000)
            break

          default:
            console.log('未知消息类型', data.type)
        }
      } catch (error) {
        console.error('处理WebSocket消息失败', error)
      }
    }

    ws.onerror = (error) => {
      console.error('WebSocket错误', error)
      ElMessage.error('WebSocket连接错误')
    }

    ws.onclose = () => {
      console.log('WebSocket连接已关闭')
      // 尝试重新连接
      setTimeout(() => {
        if (ws === null) {
          connectWebSocket()
        }
      }, 3000)
    }
  } catch (error) {
    console.error('建立WebSocket连接失败', error)
    ElMessage.error('建立WebSocket连接失败')
  }
}

// 更新用户在线状态
const updateUserStatus = (userId: string | number, isOnline: boolean) => {
  const user = userList.value.find(u => u.id === userId)
  if (user) {
    user.isOnline = isOnline
  }
}

// 更新用户输入状态
const updateUserTypingStatus = (userId: string | number, isTyping: boolean) => {
  const user = userList.value.find(u => u.id === userId)
  if (user) {
    user.isTyping = isTyping
  }
}

// 处理新消息
const handleNewMessage = (message: Message) => {
  // 如果当前正在查看该用户的聊天
  if (currentUserId.value === message.senderId) {
    messages.value.push(message)
    scrollToBottom()
  } else {
    // 更新未读消息数
    const user = userList.value.find(u => u.id === message.senderId)
    if (user) {
      user.unread = (user.unread || 0) + 1
      user.lastMessage = message.type === 'image' ? '[图片]' : message.content
      user.lastTime = '刚刚'

      // 显示消息通知
      showMessageNotification(user.nickname, message.type === 'image' ? '[图片]' : message.content)
    }
  }
}

// 显示消息通知
const showMessageNotification = (senderName: string, content: string) => {
  // 使用Element Plus的通知组件
  ElNotification({
    title: `来自 ${senderName} 的新消息`,
    message: content,
    type: 'info',
    position: 'top-right',
    duration: 4000,
    onClick: () => {
      // 查找对应的用户并选择
      const user = userList.value.find(u => u.nickname === senderName)
      if (user) {
        selectUser(user)
      }
    }
  })

  // 如果浏览器支持，同时发出声音提醒
  try {
    const audio = new Audio('/notification.mp3')
    audio.play().catch(error => {
      console.log('无法播放提示音', error)
    })
  } catch (error) {
    console.log('浏览器不支持音频播放', error)
  }
}

// 格式化时间
const formatTime = (date: Date): string => {
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 返回列表页
const goBack = () => {
  router.back()
}

// 组件卸载前关闭WebSocket连接
onBeforeUnmount(() => {
  if (ws) {
    ws.close()
    ws = null
  }

  // 清除计时器
  if (typingTimeout !== null) {
    clearTimeout(typingTimeout)
    typingTimeout = null
  }
})

onMounted(() => {
  getServiceInfo()
})
</script>

<style scoped>
.conversation-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-button {
  margin-right: 16px;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.service-info {
  display: flex;
  align-items: center;
}

.service-avatar {
  margin-right: 12px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.service-details {
  display: flex;
  flex-direction: column;
}

.service-name {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;
  color: white;
}

.service-id {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

.header-right {
  display: flex;
  align-items: center;
}

.chat-layout {
  display: flex;
  height: 650px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  background: white;
}

.chat-sidebar {
  width: 320px;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  background: #fafbfc;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  background: white;
}

.sidebar-header h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.user-search {
  width: 100%;
}

.user-search :deep(.el-input__wrapper) {
  border-radius: 20px;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.user-search :deep(.el-input__wrapper):hover {
  border-color: #c0c4cc;
}

.user-search :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  background-color: #fff;
}

.user-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.user-item {
  padding: 16px 20px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 0 12px 8px;
  border-radius: 12px;
}

.user-item:hover {
  background-color: #f0f9ff;
  transform: translateX(4px);
}

.user-item.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.user-item.active .user-name,
.user-item.active .last-message,
.user-item.active .time {
  color: white;
}

.user-avatar-wrapper {
  position: relative;
  margin-right: 12px;
}

.user-avatar {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.user-item.active .user-avatar {
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.online-indicator {
  position: absolute;
  top: -2px;
  right: -2px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #52c41a;
  border: 2px solid white;
  box-shadow: 0 0 0 1px rgba(82, 196, 26, 0.3);
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-weight: 600;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.typing-text {
  color: #409eff;
  font-style: italic;
  font-size: 12px;
  margin-left: 8px;
}

.user-item.active .typing-text {
  color: rgba(255, 255, 255, 0.9);
}

.last-message {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
}

.image-label {
  display: flex;
  align-items: center;
  gap: 4px;
}

.user-meta {
  text-align: right;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  height: 40px;
}

.time {
  font-size: 11px;
  color: #909399;
}

.unread-badge {
  margin-top: 4px;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
}

.chat-user-info {
  display: flex;
  align-items: center;
}

.chat-user-details {
  margin-left: 12px;
  flex: 1;
  min-width: 0;
}

.chat-user-name {
  font-weight: 600;
  margin-bottom: 4px;
  display: block;
  font-size: 16px;
  color: #303133;
}

.online-status {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-dot.online {
  background-color: #52c41a;
  box-shadow: 0 0 0 2px rgba(82, 196, 26, 0.2);
}

.status-dot.offline {
  background-color: #d9d9d9;
}

.chat-actions {
  display: flex;
  align-items: center;
}

.empty-chat {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.empty-content {
  text-align: center;
  color: #606266;
}

.empty-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.empty-content h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #303133;
}

.empty-content p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
}

.message-wrapper {
  margin-bottom: 20px;
}

.message-wrapper.message-self {
  display: flex;
  justify-content: flex-end;
}

.message-item {
  display: flex;
  align-items: flex-start;
  max-width: 70%;
}

.message-self .message-item {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-self .message-avatar {
  margin-left: 12px;
  margin-right: 0;
}

.message-content {
  margin: 0 12px;
  max-width: 100%;
}

.message-self .message-content {
  margin: 0 12px;
}

.message-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.message-self .message-info {
  flex-direction: row-reverse;
}

.sender-name {
  font-size: 12px;
  font-weight: 600;
  color: #606266;
}

.message-time {
  font-size: 11px;
  color: #909399;
}

.message-bubble {
  padding: 12px 16px;
  background-color: white;
  border-radius: 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  word-break: break-word;
  position: relative;
  line-height: 1.4;
  transition: all 0.3s ease;
}

.message-bubble:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.message-self .message-bubble {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.image-message {
  padding: 4px !important;
  max-width: 280px;
  overflow: hidden;
  border-radius: 12px;
}

.message-image {
  width: 100%;
  max-width: 280px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.message-image:hover {
  transform: scale(1.02);
}

.typing-indicator {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background-color: white;
  border-radius: 18px;
  margin: 0 60px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.typing-avatar {
  margin-right: 12px;
}

.typing-animation {
  display: flex;
  align-items: center;
  gap: 2px;
}

.typing-animation span {
  width: 6px;
  height: 6px;
  background-color: #409eff;
  border-radius: 50%;
  animation: typingAnimation 1.4s infinite ease-in-out;
}

.typing-animation span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-animation span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typingAnimation {

  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }

  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  background: white;
}

.input-container {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  background: #f8f9fa;
  border-radius: 24px;
  padding: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.input-container:focus-within {
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.15);
  border: 1px solid #409eff;
}

.message-input {
  flex: 1;
  border: none;
  background: transparent;
}

.message-input :deep(.el-textarea__inner) {
  border: none;
  background: transparent;
  box-shadow: none;
  resize: none;
  padding: 8px 12px;
  font-size: 14px;
  line-height: 1.4;
}

.message-input :deep(.el-textarea__inner):focus {
  box-shadow: none;
}

.input-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-btn {
  border: none;
  background: transparent;
  color: #909399;
  transition: all 0.3s ease;
}

.action-btn:hover {
  color: #409eff;
  transform: scale(1.1);
}

.send-btn {
  border-radius: 20px;
  min-width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.send-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.send-btn:disabled {
  opacity: 0.5;
  transform: none;
}

.empty-users {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 20px;
}

/* 滚动条样式 */
.user-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.user-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.user-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.user-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .conversation-detail-container {
    padding: 10px;
  }

  .chat-layout {
    height: calc(100vh - 200px);
    flex-direction: column;
  }

  .chat-sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #e4e7ed;
  }

  .detail-header {
    padding: 16px;
    flex-direction: column;
    gap: 12px;
  }

  .service-name {
    font-size: 16px;
  }
}
</style>